package com.LeetCode.String;

import org.junit.Assert;
import org.junit.Test;

/**
 * 整数转英文单词
 */
public class IntToWords {
    String[] LESS_THAN_TWENTY  = {"","One", "Two", "Three", "Four", "Five",
            "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
            "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] THOUSAND  = {"","Thousand","Million","Billion"};
    String[] HUNDRED = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    public String numberToWords(int num) {
        if(num == 0) return "Zero";

        StringBuilder strb = new StringBuilder();
        int index = 0;
        while(num > 0){
            if(num % 1000 != 0){
                StringBuilder tmp = new StringBuilder();
                Helper(num % 1000 , tmp);
                strb.insert(0,tmp.append(THOUSAND[index]).append(" "));
            }
            index++;
            num /= 1000;
        }
        return strb.toString().trim();
    }

    private void Helper(int num, StringBuilder strb){
        if(num == 0) return;
        if(num < 20) strb.append(LESS_THAN_TWENTY[num]).append(" ");
        else if(num < 100){
            strb.append(HUNDRED[num / 10]).append(" ");
            Helper(num % 10 , strb);
        }else{
            strb.append(LESS_THAN_TWENTY[num / 100]).append(" Hundred").append(" ");
            Helper(num % 100, strb);
        }
    }

    @Test
    public void test(){
        int num = 1234567891;
        Assert.assertEquals(numberToWords(num),
                "One Billion Two Hundred Thirty Four Million Five " +
                        "Hundred Sixty Seven Thousand Eight Hundred Ninety One"); ;
    }
}
